﻿using Kingdee.BOS;
using Kingdee.BOS.App.Core;
using Kingdee.BOS.App.Data;
using Kingdee.BOS.Contracts;
using Kingdee.BOS.Core;
using Kingdee.BOS.Core.BusinessFlow;
using Kingdee.BOS.Core.Permission;
using Kingdee.BOS.Log;
using Kingdee.BOS.Msg;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.Util;
using Kingdee.BOS.WebApi.FormService;
using Kingdee.K3.FIN.Core.Voucher;
using Newtonsoft.Json;
using RK.Model;
using RK.Model.BPW;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RK.MySchedule.BPW
{
    //bpw获取出口订单变更单，并自动发送邮件给采购员
    public class XSalAutoSendMail : IScheduleService
    {
        private Context context;
        public void Run(Context ctx, Schedule schedule)
        {
            this.context = ctx;
            string hostName = context.FullClientIP;
            string createDate = GetDateStr();
            //string createDate = "2024-04-04";
            string nowDate = DateTime.Now.ToString("d");
            //3、	程序取数范围：
            //A、	程序运行时间如果是周二至周五则取前一天（变更单创建日期）的订单变更单数据；
            //B、	程序运行时间如果是周一则取前三天（变更单创建日期）的订单变更单数据；
            //C、	程序只取出口订单类型,
            //D、客户要货日期-变更单创建日期小于120天
            List<List<object>> xSalList = GetXSalList(createDate, nowDate);
            string filterString = $"FCreateDate>='{createDate}'  AND FCreateDate<'{nowDate}' AND FBILLTYPEID.fnumber='XSDD02_BPW' AND FDeliveryDate-FCreateDate<140 AND FCHANGEREASON LIKE '%WebAPI变更%' ";
            if (xSalList.Count == 0)
            {
                Logger.Info("自动发送邮件给采购员", $"查询条件：{filterString},没有查到符合条件的数据");
                return;
            }


            //筛选出没有填采购员的
            List<List<object>> notPurerList = new List<List<object>>();
            //+小于60天的发给钟玉芳
            List<List<object>> List60 = new List<List<object>>();
            //筛选出填了采购员的，减掉小于60天，发给各自采购员
            List<List<object>> purerList = new List<List<object>>();
            //特定销售员的
            List<List<object>> salerList = new List<List<object>>();

            //List<SalInfos> salInfos = new List<SalInfos>();
            foreach (var xSal in xSalList)
            {
                //AddAllList(xSal, salInfos);
                if (xSal[8] == null)//没填采购员
                {
                    notPurerList.Add(xSal);
                }
                else
                {
                    purerList.Add(xSal);
                }
                if (Convert.ToString(xSal[10]) == "07.01.0004")//特定客户
                {
                    salerList.Add(xSal);
                }
            }
            Logger.Info("自动发送邮件给采购员", $"查询条件：{filterString},全部数据：{JsonConvert.SerializeObject(xSalList)}");
            if (purerList.Count > 0)//有采购员
            {
                for (int i = purerList.Count - 1; i >= 0; i--)
                {
                    //小于等于 60天；推送给钟玉芳。
                    DateTime yhDate = Convert.ToDateTime(Convert.ToDateTime(purerList[i][9]).ToString("d"));
                    DateTime cDate = Convert.ToDateTime(Convert.ToDateTime(purerList[i][0]).ToString("d"));
                    if ((yhDate - cDate).TotalDays <= 80)
                    {
                        List60.Add(purerList[i]);
                        purerList.Remove(purerList[i]);
                    }
                }
            }
            //特定客户，给特定销售人员发邮件
            List<string> sals = GetSalMailList();
            if (salerList.Count > 0)
            {
                string mailType = $"{hostName}:给特定销售人员发邮件";
                try
                {
                    AutoSenMailInfoFromXSalOrder(salerList, sals, mailType);
                    Logger.Info("自动发送邮件给采购员", $"查询条件：{filterString},特定客户数据：{JsonConvert.SerializeObject(salerList)}");
                }
                catch (Exception e)
                {
                    Logger.Info("自动发送邮件给采购员", $"特定客户报错：{e.Message};{JsonConvert.SerializeObject(sals)}");
                }

            }
            //没维护采购员给钟玉芳邮件
            List<string> zyfmail = GetZyfMail("钟玉芳");
            if (notPurerList.Count > 0)
            {
                if (zyfmail.Count > 0)
                {
                    string mailType = $"{hostName}:没维护采购员给钟玉芳邮件";
                    try
                    {
                        AutoSenMailInfoFromXSalOrder(notPurerList, zyfmail, mailType);
                        Logger.Info("自动发送邮件给采购员", $"查询条件：{filterString},没维护采购员数据：{JsonConvert.SerializeObject(notPurerList)}");
                    }
                    catch (Exception e)
                    {
                        Logger.Info("自动发送邮件给采购员", $"没维护采购员报错：{e.Message};{JsonConvert.SerializeObject(zyfmail)}");
                    }
                }
            }
            //小于60天的发给钟玉芳邮件
            if (List60.Count > 0)
            {
                if (zyfmail.Count > 0)
                {
                    string mailType = $"{hostName}:小于60天的发给钟玉芳邮件";
                    try
                    {
                        AutoSenMailInfoFromXSalOrder(List60, zyfmail, mailType);
                        Logger.Info("自动发送邮件给采购员", $"查询条件：{filterString},小于60天的数据：{JsonConvert.SerializeObject(List60)}");
                    }
                    catch (Exception e)
                    {
                        Logger.Info("自动发送邮件给采购员", $"小于60天报错：{e.Message};{JsonConvert.SerializeObject(zyfmail)}");
                    }
                }
            }
            //取员工，按采购员分组进行发送邮件
            var empInfoList = GetPurEmail(purerList);
            if (empInfoList.Count > 0)
            {
                string mailType = $"{hostName}:给对应采购员发邮件";
                foreach (var emp in empInfoList)
                {
                    if (purerList.Count > 0)
                    {
                        string empMail = GetEmpMail(emp);
                        //按员工获取变更列表，并各自发送邮件
                        if (!empMail.IsNullOrEmptyOrWhiteSpace())
                        {
                            List<List<object>> eSalList = GetESalList(purerList, emp);
                            if (eSalList.Count > 0 && !emp[0].IsNullOrEmptyOrWhiteSpace())
                            {
                                List<string> to = new List<string>();
                                to.Add(empMail);
                                try
                                {
                                    AutoSenMailInfoFromXSalOrder(eSalList, to, mailType);
                                    Logger.Info("自动发送邮件给采购员", $"查询条件：{filterString},{emp}的数据：{JsonConvert.SerializeObject(eSalList)}");
                                }
                                catch (Exception e)
                                {
                                    Logger.Info("自动发送邮件给采购员", $"采购员{emp}的报错：{e.Message};{JsonConvert.SerializeObject(to)}");
                                }
                            }
                        }
                    }
                }
            }
        }

        private void AddAllList(List<object> xSal, List<SalInfos> salInfos)
        {
            //变更日期</td><td> SAP订单号</td><td> 物料名称</td><td> 图号</td><td> 变更类型</td><td> 原数量</td><td> 新数量</td><td> 梅州交货日期</td><td> 客户要求日期
            //FCreateDate,F_BPW_SapOrder,fmaterialid.fname,F_BPW_Dwgnumber,FChangeType,FQtyX,FQty,F_BPW_DeliveryDate,fmaterialid.FPurchaserId,FDeliveryDate,FCustId.fnumber
            SalInfos sInfos = new SalInfos();
            sInfos.FCreateDate = xSal[0] == null ? "" : Convert.ToString(xSal[0]);
            sInfos.F_BPW_SapOrder = xSal[1] == null ? "" : Convert.ToString(xSal[1]);
            sInfos.fmaterialid = xSal[2] == null ? "" : Convert.ToString(xSal[2]);
            sInfos.F_BPW_Dwgnumber = xSal[3] == null ? "" : Convert.ToString(xSal[3]);
            sInfos.FChangeType = xSal[4] == null ? "" : Convert.ToString(xSal[4]);
            sInfos.FQtyX = Convert.ToDecimal(xSal[5]);
            sInfos.FQty = Convert.ToDecimal(xSal[6]);
            sInfos.F_BPW_DeliveryDate = xSal[7] == null ? "" : Convert.ToString(xSal[7]);
            sInfos.FPurchaserId = xSal[8] == null ? "" : Convert.ToString(xSal[8]);
            sInfos.FDeliveryDate = xSal[9] == null ? "" : Convert.ToString(xSal[9]);
            sInfos.FCustId = xSal[10] == null ? "" : Convert.ToString(xSal[10]);
            salInfos.Add(sInfos);
        }

        private string GetEmpMail(string emp)
        {
            string lists = "";
            var result = WebApiServiceCall.ExecuteBillQuery(this.context, Base.QueryParameter("BD_Empinfo", "FEmail", $"fname='{emp}'"));
            if (result.Count > 0)
            {
                lists = result.FirstOrDefault().FirstOrDefault().ToString();
            }
            return lists;
        }

        private List<List<object>> GetESalList(List<List<object>> purerList, string emper)
        {
            List<List<object>> lists = new List<List<object>>();
            foreach (var emp in purerList)
            {
                if (emp[8].ToString() == emper)
                {
                    lists.Add(emp);
                }
            }
            return lists;
        }

        private List<string> GetZyfMail(string v)
        {
            List<string> mails = new List<string>();
            var result = WebApiServiceCall.ExecuteBillQuery(this.context, Base.QueryParameter("BD_Empinfo", "FEmail,fname", $"fname='{v}'"));
            if (result.Count > 0)
            {
                foreach (var item in result)
                {
                    mails.Add(item[0].ToString());
                }
            }
            return mails;
        }
        /// <summary>
        /// 获取预置资料5作为特定销售员的邮箱设置信息
        /// </summary>
        /// <returns></returns>
        private List<string> GetSalMailList()
        {
            List<string> list = new List<string>();
            var result = WebApiServiceCall.ExecuteBillQuery(this.context, Base.QueryParameter("BAS_PreBaseDataFive", "fnumber,fname", ""));
            if (result.Count > 0)
            {
                foreach (var item in result)
                {
                    list.Add(item[0].ToString());
                }
            }
            return list.Distinct().ToList();
        }
        /// <summary>
        /// 获取物料对应采购员的销售订单变更单列表
        /// </summary>
        /// <param name="fdate"></param>
        /// <param name="emper"></param>
        /// <returns></returns>
        private List<List<object>> GetXSalList(string createDate, string nowDate)
        {
            string fieldKeys = "FCreateDate,F_BPW_SapOrder,fmaterialid.fname,F_BPW_Dwgnumber,FChangeType,FQtyX,FQty,F_BPW_DeliveryDate,fmaterialid.FPurchaserId,FDeliveryDate,FCustId.fnumber";
            string filterString = $"FCreateDate>='{createDate}'  AND FCreateDate<'{nowDate}' AND FBILLTYPEID.fnumber='XSDD02_BPW' AND FDeliveryDate-FCreateDate<140 AND FCHANGEREASON LIKE '%WebAPI变更%' ";
            return WebApiServiceCall.ExecuteBillQuery(this.context, Base.QueryParameter("SAL_XORDER", fieldKeys, filterString));
        }
        /// <summary>
        /// 发送邮件
        /// </summary>
        /// <param name="xSalList"></param>
        /// <param name="to"></param>
        private void AutoSenMailInfoFromXSalOrder(List<List<object>> xSalList, List<string> to, string mailType)
        {
            //var sendMailService = new SendMailService();
            // 获取邮件服务器信息，发件人信息
            //var emailInfo = sendMailService.GetEmailMessageInfoByUserId(this.context, this.context.UserId);
            EmailMessageInfo emailInfo = new EmailMessageInfo();
            //设置邮件服务器
            SetMailServer(emailInfo);
            // 设置邮件标题
            emailInfo.Subject = mailType;
            // 设置邮件内容
            SetMailBody(emailInfo, xSalList);
            // 设置邮件接收人
            emailInfo.To = to;
            //设置邮件抄送人
            //emailInfo.Cc = cc;
            try
            {
                //发送邮件
                MailUtils.Sendmail(emailInfo);
            }
            catch (Exception ex)
            {
                Logger.Info("自动发送邮件给采购员", $"{ex.Message}");
            }
            //Logger.Info("BPW", "邮件发送成功：", true);
        }
        /// <summary>
        /// 设置邮件内容
        /// </summary>
        /// <param name="emailInfo"></param>
        /// <param name="xSalList"></param>
        private void SetMailBody(EmailMessageInfo emailInfo, List<List<object>> xSalList)
        {
            string bgDate = string.Empty;//变更日期
            string salNo = string.Empty;//订单号
            string wlname = string.Empty;//物料名称
            string th = string.Empty;//图号
            string cType = string.Empty;//变更类型
            decimal oldQty = 0;//原数量
            decimal qty = 0;//新数量
            string mzjhDate = string.Empty;//梅州交货日期
            string yhDate = string.Empty;//客户要货日期
            emailInfo.Body = "<table border=" + 1 + "><tr><td> 变更日期 </td><td> SAP订单号 </td><td> 物料名称 </td><td> 图号 </td><td> 变更类型 </td><td> 原数量 </td><td> 新数量 </td><td> 梅州交货日期 </td><td> 客户要求日期 </td></tr>";
            if (xSalList.Count > 0)
            {
                foreach (var xSal in xSalList)
                {
                    bgDate = Convert.ToDateTime(xSal[0]).ToString("d");
                    salNo = xSal[1].ToString();
                    wlname = xSal[2].ToString();
                    th = xSal[3].ToString();
                    cType = GetBgType(xSal[4].ToString());
                    oldQty = Math.Round((decimal)xSal[5]);
                    qty = Math.Round((decimal)xSal[6]);
                    mzjhDate = Convert.ToDateTime(xSal[7]).ToString("d");
                    yhDate = Convert.ToDateTime(xSal[9]).ToString("d");
                    emailInfo.Body += "<tr><td>" + bgDate + "</td ><td>" + salNo + "</td><td>" + wlname + "</td><td>" + th + "</td><td>" + cType + "</td><td>" + oldQty + "</td><td>" + qty + "</td><td>" + mzjhDate + "</td><td>" + yhDate + "</td></tr>";
                }
            }
            emailInfo.Body += "</table>";
        }
        /// <summary>
        /// 设置邮件服务器
        /// </summary>
        /// <param name="emailInfo"></param>
        private void SetMailServer(EmailMessageInfo emailInfo)
        {
            emailInfo.EnableSSL = false;
            emailInfo.From = "mes@bpw.cn";
            emailInfo.FromName = "金蝶云星空自动邮件";
            emailInfo.IsBodyHtml = true;
            emailInfo.IsMailBCC = false;
            emailInfo.Password = "bpwmz2022";
            emailInfo.Protocol = EmailProtocol.POP3;
            emailInfo.PwdDecode = true;
            emailInfo.SendType = EmailSendType.Default;
            emailInfo.SmtpHost = "61.143.205.219";
            emailInfo.SmtpPort = 25;
            emailInfo.UserName = "mes@bpw.cn";
        }
        /// <summary>
        /// 变更类型
        /// </summary>
        /// <param name="v"></param>
        /// <returns></returns>
        private string GetBgType(string v)
        {
            string bgType = "";
            switch (v)
            {
                case "A":
                    bgType = "新增";
                    break;
                case "B":
                    bgType = "修改";
                    break;
                case "D":
                    bgType = "删除";
                    break;
                case "T":
                    bgType = "终止";
                    break;
                default:
                    bgType = "关闭";
                    break;
            }
            return bgType;
        }
        /// <summary>
        /// 获取采购员邮箱地址
        /// </summary>
        /// <returns></returns>
        private List<string> GetPurEmail(List<List<object>> purerList)
        {
            List<string> lists = new List<string>();
            if (purerList.Count > 0)
            {
                foreach (var purer in purerList)
                {
                    string emp = purer[8].ToString();
                    lists.Add(emp);
                }
            }
            var newList = lists.Distinct().ToList();
            return newList;
        }

        /// <summary>
        /// 如果是星期六、日，取前三天，否则取前一天的短日期
        /// 2024-01-08，逻辑改为取前一天的
        /// </summary>
        /// <returns></returns>
        private string GetDateStr()
        {
            string dateStr = "2020-01-01";
            var now = DateTime.Now;
            dateStr = now.AddDays(-1).ToString("d");
            //int dayOfweek = (int)now.DayOfWeek;
            //if (dayOfweek > 1 && dayOfweek < 6)
            //{
            //    dateStr = now.AddDays(-1).ToString("d");
            //}
            //else if (dayOfweek == 1)
            //{
            //    dateStr = now.AddDays(-3).ToString("d");
            //}
            //else
            //{

            //}
            return dateStr;
        }
    }

    internal class SalInfos
    {
        //变更日期</td><td> SAP订单号</td><td> 物料名称</td><td> 图号</td><td> 变更类型</td><td> 原数量</td><td> 新数量</td><td> 梅州交货日期</td><td> 客户要求日期
        //FCreateDate,F_BPW_SapOrder,fmaterialid.fname,F_BPW_Dwgnumber,FChangeType,FQtyX,FQty,F_BPW_DeliveryDate,fmaterialid.FPurchaserId,FDeliveryDate,FCustId.fnumber
        /// <summary>
        /// 变更单创建日期
        /// </summary>
        public string FCreateDate { get; set; }
        /// <summary>
        /// SAP订单号
        /// </summary>
        public string F_BPW_SapOrder { get; set; }
        /// <summary>
        /// 物料名称
        /// </summary>
        public string fmaterialid { get; set; }
        /// <summary>
        /// 图号
        /// </summary>
        public string F_BPW_Dwgnumber { get; set; }
        /// <summary>
        /// 变更类型
        /// </summary>
        public string FChangeType { get; set; }
        /// <summary>
        /// 原数量
        /// </summary>
        public decimal FQtyX { get; set; }
        /// <summary>
        /// 新数量
        /// </summary>
        public decimal FQty { get; set; }
        /// <summary>
        /// 梅州交货日期
        /// </summary>
        public string F_BPW_DeliveryDate { get; set; }
        /// <summary>
        /// 采购员
        /// </summary>
        public string FPurchaserId { get; set; }
        /// <summary>
        /// 客户要求日期
        /// </summary>
        public string FDeliveryDate { get; set; }
        /// <summary>
        /// 客户编码
        /// </summary>
        public string FCustId { get; set; }
    }
}
